package com.zxc.service;

import cn.hutool.core.bean.BeanUtil;
import com.zxc.common.ErrorCode;
import com.zxc.common.exception.BusinessException;
import com.zxc.oj.model.entity.User;
import com.zxc.oj.model.enums.UserRoleEnum;
import com.zxc.oj.model.vo.UserVO;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.List;

import static com.zxc.common.constant.UserConstant.USER_LOGIN_STATE;

/**
 * <p>
 * 用户 服务类
 * </p>
 *
 * @author author
 * @since 2024-02-10
 */
@FeignClient(name = "oj-backend-user-service", path = "/api/user/inner")
public interface UserFeignClient {


    /**
     * 根据id获取用户
     *
     * @param id
     * @return
     */
    @GetMapping("/get/id")
    User getById(@RequestParam("id") long id);


    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    default User getLoginUser(HttpServletRequest request) {

        // 先判断是否已登录
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null || currentUser.getId() == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return currentUser;
    }

    /**
     * 根据id集合获取用户集合
     */
    @GetMapping("/get/ids")
    List<User> listByIds(@RequestParam("ids") Collection<Long> ids);

    /**
     * 是否为管理员
     *
     * @param user
     * @return
     */
    default boolean isAdmin(User user) {
        return user.getUserRole().equals(UserRoleEnum.ADMIN);
    }

    /**
     * 获取用户脱敏信息
     *
     * @param user
     * @return
     */

    default UserVO getUserVO(User user) {
        UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
        userVO.setUserRole(user.getUserRole().getValue());
        return userVO;
    }


}
